import { useEffect, useState, useRef, useCallback } from 'react';
import './styleSearch.scss';
import { SearchOutlined, CameraOutlined, CloseOutlined, EllipsisOutlined } from '@ant-design/icons';
import { Button, Input, Dropdown, Tooltip } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import hot from '../../assets/img/hot.jpg'
import { setSearchValue, setSuggestions, clearSuggestions } from '../../pages/store/modules/slice'; // 更新导入
// 在文件顶部添加节流函数
function throttle<T extends (...args: any[]) => void>(func: T, limit: number): T {
  let lastFunc: ReturnType<typeof setTimeout>;
  let lastRan: number;
  return function(this: any, ...args: Parameters<T>) {
    const context = this;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(() => {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  } as T;
}
function SearchBar() {

  // 定义是否聚焦状态
  const [isFocused, setIsFocused] = useState(false);
  // 定义搜索框的引用
  const searchRef = useRef<HTMLDivElement>(null);
  // 定义包裹搜索框的引用
  const wrapperRef = useRef<HTMLDivElement>(null);
  // 定义是否固定状态
  const [isFixed, setIsFixed] = useState(false);
  // 控制上传弹窗
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [showEllipsisMenu, setShowEllipsisMenu] = useState(false);
 // 新增：用于保存原始高度的引用
  const originalHeightRef = useRef<number>(0);
  // 新增：占位元素引用
  const placeholderRef = useRef<HTMLDivElement>(null);

  const dispatch = useDispatch();
  const { searchValue, suggestions } = useSelector((state: any) => state.search);
  // 防抖函数
  const debounceRef = useRef<NodeJS.Timeout | null>(null);

  // 模拟获取联想数据
  const fetchSuggestions = useCallback((value: string) => {
    if (!value) {
      dispatch(clearSuggestions());
      return;
    }

    // 模拟API请求延迟
    setTimeout(() => {
      if (value.includes('端午')) {
        dispatch(setSuggestions({
          templates: [
            '端午海报', '端午放假通知', '端午活动', '端午节活动',
            '端午放假', '端午节放假', '端午节公众号', '端午一双节', '端午系列海报'
          ],
          tools: ['按工具搜索"端午"'],
          categories: ['AI电商素材', 'AI端午节素材']
        }));
      } else if (value) {
        dispatch(setSuggestions({
          templates: [
            `${value}海报`, `${value}活动`, `${value}通知`,
            `${value}系列`, `${value}设计`
          ],
          tools: [`按工具搜索"${value}"`],
          categories: [`AI${value}素材`, `${value}设计素材`]
        }));
      }
    }, 300);
  }, [dispatch]);

  // 输入处理函数（带防抖）
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    dispatch(setSearchValue(value));

    // 清除之前的防抖计时器
    if (debounceRef.current) {
      clearTimeout(debounceRef.current);
    }

    // 设置新的防抖计时器
    debounceRef.current = setTimeout(() => {
      fetchSuggestions(value);
    }, 300);
  };

  // 处理搜索
  const handleSearch = () => {
    // 实际搜索逻辑...
    console.log('执行搜索:', searchValue);
    setIsFocused(false);
  };

  // 处理联想项点击
  const handleSuggestionClick = (suggestion: string) => {
    dispatch(setSearchValue(suggestion));
    // 可以立即执行搜索
    handleSearch();
  };

  // 组件卸载时清除定时器
  useEffect(() => {
    return () => {
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
      }
    };
  }, []);


  // 点击相机图标处理函数
  const handleCameraClick = () => {
    setShowUploadModal(true);
    setIsFocused(false); // 关闭搜索框聚焦状态
  };
  // 定义下拉菜单项
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
          稿定模版
        </a>
      ),
    },
    {
      key: '2',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.aliyun.com">
          团队空间
        </a>
      ),


    },
    {
      key: '3',
      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
          我的空间
        </a>
      ),

    },
    {
      key: '4',

      label: (
        <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
          素材下载
        </a>
      )
    },
  ];


  // 处理点击外部区域关闭
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) {
        setIsFocused(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // 滚动监听
  // 修改后的 useEffect 滚动监听部分
   useEffect(() => {
    const searchElement = searchRef.current;
    if (!searchElement) return;

    // 保存初始高度
    if (originalHeightRef.current === 0) {
      originalHeightRef.current = searchElement.offsetHeight;
    }

    // 使用getBoundingClientRect()获取初始位置
    const initialRect = searchElement.getBoundingClientRect();
    const initialOffset = initialRect.top + window.scrollY;

    const handleScroll = () => {
      const scrollY = window.scrollY || document.documentElement.scrollTop;
      const shouldFix = scrollY > initialOffset;
      
      // 使用函数式更新确保状态一致性
      setIsFixed(prev => {
        if (prev !== shouldFix) {
          // 设置占位元素高度
          if (placeholderRef.current) {
            placeholderRef.current.style.height = shouldFix 
              ? `${originalHeightRef.current}px` 
              : '0';
          }
          return shouldFix;
        }
        return prev;
      });
    };

    // 使用节流函数包装滚动处理
    const throttledHandleScroll = throttle(handleScroll, 50);

    throttledHandleScroll(); // 初始执行一次
    window.addEventListener('scroll', throttledHandleScroll);
    
    return () => {
      window.removeEventListener('scroll', throttledHandleScroll);
    };
  }, []); // 移除 isFixed 依赖



  // 数据
  const listData = [
    {
      id: 1,
      title: '端午',
      img: 'https://gd-filems.dancf.com/gaoding/gaoding/53357/096f894b1f814abfa3b8ed2eed6859af.jpg?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp',
      hot: hot,
      bg: {
        backgroundImage: 'linear-gradient(to right,rgba(255, 230, 230,0.8) 0%,  rgb(255, 247, 247,0.2) 100%)'
      },
      color: {
        backgroundColor: '#f7e2e2'
      }
    },
    {
      id: 2,
      title: '文章长图',
      img: 'https://gd-filems.dancf.com/gaoding/gaoding/53357/e8c64c5dd4bd4d04bfebbc4816baa73e.png?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp',

    },
    {
      id: 3,
      title: '六一',
      img: 'https://gd-filems.dancf.com/gaoding/gaoding/53357/14a2d0220d00476eb17449f81fdd0e65.jpg?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp',
      hot: hot,
      bg: {
        backgroundImage: 'linear-gradient(to right,rgba(255, 240, 228,0.8) 0%, rgba(255, 249, 245,0.2) 100%)'
      },
      color: {
        backgroundColor: '#f7e9e0'
      }

    },
    {
      id: 4,
      title: '长图',
      img: 'https://gd-filems.dancf.com/gaoding/gaoding/53357/81de0c069f5b44d2b25174e7d378094d.jpg?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp'

    },
    {
      id: 5,
      title: '表格',
      img: 'https://st0.dancf.com/02/cms/202505151153-03b5.jpg?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp',
      bg: {
        backgroundImage: 'linear-gradient(to right,rgba(249, 243, 214,0.8) 0%,  rgba(255, 254, 245,0.2) 100%)'
      },
      color: {
        backgroundColor: '#f7f2d9'
      }

    },
    {
      id: 6,
      title: '高考',
      img: 'https://gd-filems.dancf.com/gaoding/gaoding/29681/a1fee2d27ec34234b0204d357fd6953d.jpg?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp',
      hot: hot
    },
    {
      id: 7,
      title: '小红书配图',
      img: 'https://gd-filems.dancf.com/gaoding/gaoding/90882/d436a13e2dea43fb8666142aaf61d3ed.jpg?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp',

    },
    {
      id: 8,
      title: '气泡',
      img: 'https://gd-filems.dancf.com/gaoding/gaoding/57007/69b02547c1fc4459b76b0001283ea57a.gif?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp',

    },
    {
      id: 9,
      title: '边框',
      img: 'https://gd-filems.dancf.com/gaoding/gaoding/84627/a2c2bf6c-7e3a-43b0-a653-5d1b6166852e103468.jpg?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp',

    },
    {
      id: 10,
      title: '龙舟',
      img: 'https://gd-filems.dancf.com/gaoding/gaoding/53357/053f9f0cb6414e978e3002caf3bf7677.jpg?x-oss-process=image/resize,w_98/crop,w_56,h_95,g_north/interlace,1/format,webp',

    },

  ]

  return (
    <>
       <div 
        ref={placeholderRef} 
        style={{ 
          height: '0', 
          transition: 'height 0.3s ease',
          visibility: 'hidden' 
        }}
      />
      <div
        ref={searchRef}

        className={`search ${isFixed ? 'fixed' : ''}`} // 此处改为动态类名
      >
        {/* 新增条件渲染的图标 */}
        {isFixed && (
          <div
            className="fixed-ellipsis"
            onMouseEnter={() => setShowEllipsisMenu(true)}
            onMouseLeave={() => setShowEllipsisMenu(false)}
          >
            <EllipsisOutlined style={{ color: '#000' }} />
            {/* 添加弹窗 */}
            {showEllipsisMenu && (
              <div className="ellipsis-menu">
                <div className="menu-item">模板素材</div>
                <div className="menu-item">设计场景</div>
                <div className="menu-item">工具推荐</div>
                <div className="menu-item">资源教程</div>
              </div>
            )}
          </div>
        )}

        {/* 搜索框 */}
        <div ref={wrapperRef} className="search-wrapper">
          <Input
            className={`input ${isFocused ? 'input-focused' : ''}`}
            style={{ width: '650px', height: '55px' }}
            placeholder="请输入关键词"
            value={searchValue}
            onChange={handleInputChange}
            onFocus={() => setIsFocused(true)}
            prefix={<SearchOutlined style={{ color: 'rgba(0,0,0,.25)', fontSize: '20px' }} />}
            suffix={
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Tooltip title="上传图片搜相似模版" placement="bottom">
                  <CameraOutlined
                    onClick={handleCameraClick}
                    style={{
                      color: 'rgba(0,0,0,.45)',
                      fontSize: '20px',
                      cursor: 'pointer',
                      display: 'inline-block'
                    }}
                    className='camera'
                  />
                </Tooltip>
                <Button
                  size='large'
                  className='btn'
                  style={{
                    background: 'linear-gradient(85deg, #275afb 0%, #3599fe 100%)',
                    color: '#fff',
                    border: 'none',
                    height: 45,
                    padding: '0 20px'
                  }}
                  onClick={handleSearch}
                >
                  搜索
                </Button>
              </div>
            }
          />

          {/* 左侧下拉框 */}
          {isFocused && (
            <div className="dropdown-panel left">
              <Dropdown
                menu={{ items }}
                placement="bottomLeft"
                getPopupContainer={() => wrapperRef.current!}
              >
                <a onClick={(e) => e.preventDefault()}>
                  稿定模版
                  <DownOutlined />
                </a>
              </Dropdown>
            </div>
          )}

          {/* 下方内容盒子 */}
          {isFocused && (
            <div className="content-box bottom">
              {searchValue ? (
                // 显示联想搜索内容
                <div className="suggestion-container">
                  {/* 模板部分 */}
                  <div className="suggestion-section">
                  
                    <div className="suggestion-items">
                      {suggestions.templates.map((item, index) => (
                        <div
                          key={index}
                          className="suggestion-item"
                          onClick={() => handleSuggestionClick(item)}
                        >
                          <span className="suggestion-text">Q {item}</span>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* 工具部分 */}
                  <div className="suggestion-section">
                    <h4>{suggestions.tools[0]}</h4>
                  </div>

                  {/* 分类部分 */}
                  <div className="suggestion-section">
                    <h4>AI电商素材</h4>
                    <div className="suggestion-items">
                      {suggestions.categories.map((item, index) => (
                        <div
                          key={index}
                          className="suggestion-item"
                          onClick={() => handleSuggestionClick(item)}
                        >
                          <span className="suggestion-text">{item}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              ) : (
                // 显示热门搜索内容
                <>
                  <h4>大家都在搜<img src="https://cdn.dancf.com/fe-assets/20241206/6ffff94e20e122666ad8076c61f96999.svg" alt="" /></h4>
                  <div className="content-list">
                    {listData.map((item) => (
                      <div className="content-item" key={item.id} style={item.bg}>
                        <div className="conent-img" style={item.color}>
                          <img src={item.img} alt="" />
                        </div>
                        <div style={{ margin: '0px 10px' }}>{item.title}</div>
                        <span>{item.hot && <img src={item.hot} alt="" />}</span>
                      </div>
                    ))}
                  </div>
                </>
              )}
            </div>
          )}
        </div>
        {/* 图片上传弹窗 */}
        {showUploadModal && (
          <div className="upload-modal">
            <div className="upload-content">
              <h3>以图搜图</h3>
              <div className="upload-area">
                <p>拖拽图片到这里，或者点击下方按钮上传</p>
                <div className="upload-buttons">
                  <Button>手机上传</Button>
                  <Button>本地上传</Button>
                </div>
              </div>
              <CloseOutlined
                className="close-icon"
                onClick={() => setShowUploadModal(false)}
              />
            </div>
          </div>
        )}
      </div>
    </>

  )
}

export default SearchBar;